package com.powernode.listener;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.powernode.constant.Constants;
import com.powernode.entity.Orders;
import com.powernode.service.impl.DelayMessageService;
import com.powernode.service.impl.OrderServiceImpl;
import jakarta.annotation.Resource;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import com.rabbitmq.client.Channel;

import java.io.IOException;


@Component
public class OrderListener {

    @Resource
    private OrderServiceImpl orderService;
    @Resource
    private ObjectMapper objectMapper;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private DelayMessageService delayMessageService;

    @RabbitListener(queues = Constants.QUEUE_NAME_ORDER ,concurrency = "6")
    public void onMessage(Message message , Channel  channel){
        long tag = message.getMessageProperties().getDeliveryTag();
        try {

            //1.获取orders消息将json数据转换成orders对象
            Orders orders = objectMapper.readValue(message.getBody(), Orders.class);
            //2.调用service方法进行秒杀
            int orderResult = orderService.doOrder(orders);

            if (orderResult == 1){
                //3.将结果保存到redis中
                redisTemplate.opsForValue().set(Constants.REDIS_RESULT+orders.getGoodsId() + ":" + orders.getUid(), orders);
                //4.确认消息
                channel.basicAck(tag, false);

                //发送消息
                delayMessageService.sendDelayMessage(orders.getId());
                return;
            }
            //5.处理失败，将消息重新放回队列
            channel.basicNack(tag, false, true);
        } catch (Exception e) {

            try {
                channel.basicNack(tag, false, true);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
            throw new RuntimeException(e);
        }
    }
}
